#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
@Project: kubeext-SDS 
@File: pool.py
@Author: admin
@Date: 2022/6/7 14:17 
@desc: 
"""
import os
import shutil

from testconstant import LOCAL_FS_URL, NFS_URL, LOCAL_FS_OPT, NFS_OPT, CEPH_DEV_URL, CEPH_DEV_OPT, NFS, \
    LOCAL_FS, CEPH_DEV, KUBESDS_TEST_STORAGE_TYPE, VMD, SANDSTONE, KUBESDS_TEST_BLOCK_STORAGE_TYPE, SANDSTONE_OPT, \
    SANDSTONE_URL
from util import getArgparseParam, get_random_uuid, get_cstor_pool
from utils.adm_exc.parsers import createPoolParser, deletePoolParser, showPoolParser
from utils.constant.constant import KUBESDS_TEST_ENV_VALUE, KUBESDS_TEST_ENV_KEY, KUBESDS_LOG, VIRTUAL_MACHINE_POOL
from utils.exception import KubdesdsExecuteException
from utils.logger import set_logger
from utils.utils import create_all_jsondict, get_pool_info, K8SInfoUtil

logger = set_logger(os.path.basename(__file__), KUBESDS_LOG)


def poolTest(pool_type):
    """
    存储池相关测试
    :param pool_type: localfs|nfs|ceph_dev
    :return:
    """
    logger.debug('\n\n')
    logger.debug('***kubesds test pool start.')
    # 设置测试时，特有的环境变量内容
    os.environ[KUBESDS_TEST_ENV_KEY] = KUBESDS_TEST_ENV_VALUE
    try:
        if pool_type not in KUBESDS_TEST_STORAGE_TYPE:
            raise KubdesdsExecuteException('kubesdsTestError',
                                           'kubesds test pool type not in [%s|%s|%s].' % KUBESDS_TEST_STORAGE_TYPE)

        pool_uuid = get_random_uuid()
        pool = get_random_uuid()
        content = VMD
        # 1.创建存储（文件系统类型默认会开启，未设置自启动）
        createPoolTest(pool_type, pool_uuid, pool, content)
        # 2.显示存储
        showPoolTest(pool_type, pool)
        # 3.删除存储
        deletePoolTest(pool_type, pool, pool_uuid)
    except Exception as e:
        raise KubdesdsExecuteException('kubesdsTestError', 'pool test error.')
    finally:
        # 去除测试时特有的环境变量内容
        if KUBESDS_TEST_ENV_KEY in os.environ:
            del os.environ[KUBESDS_TEST_ENV_KEY]


def createPoolTest(pool_type, pool_uuid, pool, content):
    """
    创建存储池测试（当前只测试localfs|nfs|ceph_dev类型，其余未测试）
    :param pool_type: localfs|nfs|ceph_dev
    :param pool_uuid: 数据库中的msid值（界面上可以直接查看）
    :param pool: 表cl_hostlocalstorage_inf对应的poolname
    :param content: 存储：vmd, 镜像服务器：vmdi
    :return:
    """
    create_pool_params = {}
    if pool_type == LOCAL_FS:
        url = LOCAL_FS_URL
        if not os.path.exists(url):
            os.makedirs(url)
        opt = LOCAL_FS_OPT
    elif pool_type == NFS:
        url = NFS_URL
        opt = NFS_OPT
    elif pool_type == CEPH_DEV:
        url = CEPH_DEV_URL
        opt = CEPH_DEV_OPT
    elif pool_type == SANDSTONE:
        url = SANDSTONE_URL
        opt = SANDSTONE_OPT
    else:
        raise KubdesdsExecuteException('kubesdsTestError', 'pool type error.')

    create_pool_params = {
        'type': pool_type,
        'pool': pool,
        'autostart': None,
        'content': content,
        'uuid': pool_uuid,  # 对应为msid值
        'opt': opt,
        'url': url
    } if create_pool_params is not None else create_pool_params

    if create_pool_params:
        createPoolParser(getArgparseParam(create_pool_params))
        # 注册新创建的存储至k8s中
        registerPoolToK8sTest(pool_type, pool, pool_uuid, content)

        logger.debug('***kubesds create test pool [%s] success.' % pool)


def registerPoolToK8sTest(pool_type, pool, pool_uuid, content):
    """
    注册创建测试存储至k8s中（通过上述创建的存储，并未注册至k8s中，此处重新注册）
    :param pool_type: localfs|nfs|ceph_dev
    :param pool_uuid: 数据库中的msid值（界面上可以直接查看）
    :param pool: 表cl_hostlocalstorage_inf对应的poolname
    :param content: 存储内容：vmd（存储池），vmdi（镜像服务器）
    :return:
    """
    jsondicts = []
    pool_jsondict = None
    pool_k8s_info_util = K8SInfoUtil(VIRTUAL_MACHINE_POOL, pool)
    # ceph-dev类型存储信息获取
    if pool_type in KUBESDS_TEST_BLOCK_STORAGE_TYPE:
        ceph_dev_pool_info = get_cstor_pool(pool_uuid)
        pool_info = {
            'autostart': 'no',
            'capacity': ceph_dev_pool_info['total'],
            'cephmons': ceph_dev_pool_info['ceph_mons'],
            'cephpools': ceph_dev_pool_info['ceph_pools'],
            'content': content,
            'free': ceph_dev_pool_info['free'],
            'path': pool_uuid,
            'pool': pool,
            'poolname': pool_uuid,
            'pooltype': pool_type,
            'state': ceph_dev_pool_info['status'],
            'uuid': pool,
        }
    # 文件系统类型存储信息获取
    else:
        pool_info = get_pool_info(pool_uuid)
    if pool_info:
        pool_jsondict = pool_k8s_info_util.get_create_str(pool_info)
    if pool_jsondict:
        jsondicts.append(pool_jsondict)
    if jsondicts:
        create_all_jsondict(jsondicts)


def showPoolTest(pool_type, pool):
    """
    显示存储池测试（当前只测试localfs|nfs|ceph_dev类型，其余未测试）
    :param pool_type: localfs|nfs|ceph_dev
    :param pool: 表cl_hostlocalstorage_inf对应的poolname
    :return
    """
    show_pool_params = {
        'type': pool_type,
        'pool': pool,
    }

    showPoolParser(getArgparseParam(show_pool_params))

    logger.debug('***kubesds show test pool [%s] success.' % pool)


def deletePoolTest(pool_type, pool, pool_uuid):
    """
    删除存储池测试（当前只测试localfs|nfs|ceph_dev类型，其余未测试）
    :param pool_type: localfs|nfs|ceph_dev
    :param pool: 表cl_hostlocalstorage_inf对应的poolname
    :param pool_uuid: 数据库中的msid值（界面上可以直接查看）
    :return
    """
    pool_info = get_cstor_pool(pool_uuid)

    delete_pool_params = {
        'type': pool_type,
        'pool': pool,
    }

    deletePoolParser(getArgparseParam(delete_pool_params))

    if pool_type == LOCAL_FS:
        # 本地存储删除后，会删除对应的存储目录（此操作仅此测试适用，真实环境中不存在下述操作）
        path = pool_info['mountpath']
        shutil.rmtree(path)

    logger.debug('***kubesds delete test pool [%s] success.' % pool)


if __name__ == '__main__':
    poolTest(SANDSTONE)
    # poolTest(NFS)
    # poolTest(CEPH_DEV)
